package activities;

import factories.ActivityIconListFactory;
import helper.FBHelper;
import helper.GetFBUserPhotoHelper;
import helper.HttpHelper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.Response;
import com.facebook.Session;
import com.matchcalendar.R;

import dataFormat.CalendarTextData;
import dataFormat.FBUser;

import algorithm.CalendarAlgorithm;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

public class AddMatchGroupActivity extends Activity {
	private Spinner spinnerIcon;
	private Button buttonStartDate, buttonNext, buttonOverDate, buttonPrevious, buttonActivityStartTime,
	buttonActivityOverTime;
	private EditText editTextActivityName, editTextActivityPlace, editTextInvitePeople, editTextActivityPS;
	private ImageButton imageButtonGoogleMap;
	private final int GOOGLEMAP_REQUEST_CODE = 0;
	private final int MATCH_REQUEST_CODE = 1;
	private final int PICK_FRIENDS_ACTIVITY = 2;
	private final int FINISH_SCHEDULE_REQUEST_CODE = 3;
	private Calendar matchStartCal = Calendar.getInstance();
	private Calendar matchEndCal = Calendar.getInstance();
	private Calendar activityStartTimeCal = Calendar.getInstance();
	private Calendar activityOverTimeCal = Calendar.getInstance();
	private Map<String, FBUser> idFriendMap = new HashMap<String, FBUser>();
	private Set<View> isComplete = new HashSet<View>();
	private CheckBox checkBoxAdvanceTimeChoose;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Bundle bundle = getIntent().getExtras();
		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_addmatchgroup);
		findView();
		setListenerOrAdapter();
		if (bundle.getInt("comeFrom") == 1)
			setBundleDataFromActivity(bundle);
		else if (bundle.getInt("comeFrom") == 2)
			setBundleDataFromShake(bundle);
	}

	private void findView() {
		spinnerIcon = (Spinner) findViewById(R.id.spinnerIcon);
		buttonStartDate = (Button) findViewById(R.id.buttonStartDate);
		editTextActivityName = (EditText) findViewById(R.id.editTextActivityName);
		editTextActivityPlace = (EditText) findViewById(R.id.editTextActivityPlace);
		imageButtonGoogleMap = (ImageButton) findViewById(R.id.imageButtonGoogleMap);
		editTextInvitePeople = (EditText) findViewById(R.id.editTextInvitePeople);
		editTextActivityPS = (EditText) findViewById(R.id.editTextActivityPS);
		buttonPrevious = (Button) findViewById(R.id.buttonPrevious);
		buttonNext = (Button) findViewById(R.id.buttonNext);
		buttonOverDate = (Button) findViewById(R.id.buttonOverDate);
		buttonActivityStartTime = (Button) findViewById(R.id.buttonActivityStartTime);
		buttonActivityOverTime = (Button) findViewById(R.id.buttonActivityOverTime);
		checkBoxAdvanceTimeChoose = (CheckBox) findViewById(R.id.checkBoxAdvanceTimeChoose);
	}
	
	private void setListenerOrAdapter() {
		spinnerIcon.setAdapter(new SpinnerIconAdapter(AddMatchGroupActivity.this,
				android.R.layout.simple_spinner_dropdown_item, ActivityIconListFactory.newArrayList()));
		editTextActivityName.setOnTouchListener(new EditTextTouch());
		editTextActivityName.setOnFocusChangeListener(new EditTextFocusChange("活動名稱"));
		editTextActivityPlace.setOnTouchListener(new EditTextTouch());
		editTextActivityPlace.setOnFocusChangeListener(new EditTextFocusChange("活動地點"));
		imageButtonGoogleMap.setOnClickListener(new ImageButtonGoogleMapClickListener());
		buttonStartDate.setOnClickListener(new ButtonStartDateClickListener());
		buttonOverDate.setOnClickListener(new ButtonOverDateClickListener());
		buttonActivityStartTime.setOnClickListener(new ButtonActivityStartTimeClick());
		buttonActivityOverTime.setOnClickListener(new ButtonActivityOverTimeClick());
		editTextInvitePeople.setOnTouchListener(new EditTextInvitePeopleFocusTouchListener());
		editTextActivityPS.setOnTouchListener(new EditTextTouch());
		editTextActivityPS.setOnFocusChangeListener(new EditTextFocusChange("備註"));
		buttonPrevious.setOnClickListener(new ImageButtonPreviousClickListener());
		buttonNext.setOnClickListener(new ButtonNextClick());
		checkBoxAdvanceTimeChoose.setOnCheckedChangeListener(new CheckBoxAdvanceTimeChooseCheckedChange());
	}
	
	private class SpinnerIconAdapter extends ArrayAdapter<Integer> {
		private SpinnerIconAdapter(Context context, int textViewResourceId, List<Integer> objects) {
			super(context, textViewResourceId, objects);
		}

		@Override
        public View getDropDownView(int position, View convertView,ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        	return getCustomView(position, convertView, parent);
        }
 
        private View getCustomView(int position, View convertView, ViewGroup parent) {
        	View row = getLayoutInflater().inflate(R.layout.custom_image_view, parent, false);
        	
            ((ImageView)row.findViewById(R.id.imageViewIcon)).setImageResource(getItem(position));
            return row;
        }
	}
	
	private class EditTextTouch implements EditText.OnTouchListener {

		@Override
		public boolean onTouch(View view, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN && !isComplete.contains(view)) {
				((TextView)view).setText("");
				isComplete.add(view);
			}
			return false;
		}
	}
	
	private class EditTextFocusChange implements EditText.OnFocusChangeListener {
		private String str;
		
		public EditTextFocusChange(String str) {
			this.str = str;
		}

		@Override
		public void onFocusChange(View view, boolean hasFocus) {
			if (!hasFocus && ((EditText)view).getText().toString().equals("")) {
				isComplete.remove(view);
				((EditText)view).setText(str);
			}
		}
	}
	
	private class ImageButtonGoogleMapClickListener implements ImageButton.OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(AddMatchGroupActivity.this, GoogleMapActivity.class);
			
			startActivityForResult(intent, GOOGLEMAP_REQUEST_CODE);
		}
	}
	
	private class ButtonStartDateClickListener implements Button.OnClickListener {
		
		@Override
		public void onClick(View v) {
			DatePicker startDatePicker = new DatePicker(AddMatchGroupActivity.this);
			
			startDatePicker.init(matchStartCal.get(Calendar.YEAR), matchStartCal.get(Calendar.MONTH), matchStartCal.get(Calendar.DATE), null);
			startDatePicker.setCalendarViewShown(false);
			startDatePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
			new AlertDialog.Builder(AddMatchGroupActivity.this)
			.setTitle("選擇媒合開始日期")
			.setView(startDatePicker)
			.setNegativeButton("取消", null)
			.setPositiveButton("確定", new StartDatePickerDialogPositiveClickListener(startDatePicker))
			.show();
		}
		
		private class StartDatePickerDialogPositiveClickListener implements DialogInterface.OnClickListener {
			private DatePicker startDatePicker;

			public StartDatePickerDialogPositiveClickListener(DatePicker startDatePicker) {
				this.startDatePicker = startDatePicker;
			}

			@Override
			public void onClick(DialogInterface dialog, int which) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
				
				matchStartCal.set(startDatePicker.getYear(), startDatePicker.getMonth(), startDatePicker.getDayOfMonth());
				buttonStartDate.setText(sdf.format(matchStartCal.getTime()));
				isComplete.add(buttonStartDate);
			}
		}
	}
	
	private class ButtonOverDateClickListener implements Button.OnClickListener {

		@Override
		public void onClick(View v) {
			DatePicker endDatePicker = new DatePicker(AddMatchGroupActivity.this);
			
			endDatePicker.init(matchEndCal.get(Calendar.YEAR), matchEndCal.get(Calendar.MONTH), matchEndCal.get(Calendar.DATE), null);
			endDatePicker.setCalendarViewShown(false);
			endDatePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
			new AlertDialog.Builder(AddMatchGroupActivity.this)
			.setTitle("選擇媒合結束日期")
			.setView(endDatePicker)
			.setNegativeButton("取消", null)
			.setPositiveButton("確定", new OverDatePickerDialogPositiveClickListener(endDatePicker))
			.show();
		}
		
		private class OverDatePickerDialogPositiveClickListener implements DialogInterface.OnClickListener {
			private DatePicker endDatePicker;

			public OverDatePickerDialogPositiveClickListener(DatePicker endDatePicker) {
				this.endDatePicker = endDatePicker;
			}

			@Override
			public void onClick(DialogInterface dialog, int which) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
				
				matchEndCal.set(endDatePicker.getYear(), endDatePicker.getMonth(), endDatePicker.getDayOfMonth());
				buttonOverDate.setText(sdf.format(matchEndCal.getTime()));
				isComplete.add(buttonOverDate);
			}
		}
	}
	
	private class ButtonActivityStartTimeClick implements Button.OnClickListener {

		@Override
		public void onClick(View arg0) {
			TimePicker timePicker = new TimePicker(AddMatchGroupActivity.this);
			
			timePicker.setIs24HourView(true);
			timePicker.setCurrentHour(activityStartTimeCal.get(Calendar.HOUR_OF_DAY));
			timePicker.setCurrentMinute(activityStartTimeCal.get(Calendar.MINUTE));
			timePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
			new AlertDialog.Builder(AddMatchGroupActivity.this)
			.setTitle("選擇活動開始時間")
			.setView(timePicker)
			.setNegativeButton("取消", null)
			.setPositiveButton("確定", new StartTimePickerDialogPositiveClick(timePicker))
			.show();
		}
		
		private class StartTimePickerDialogPositiveClick implements DialogInterface.OnClickListener {
			private TimePicker timePicker;

			public StartTimePickerDialogPositiveClick(TimePicker timePicker) {
				this.timePicker = timePicker;
			}

			@Override
			public void onClick(DialogInterface dialog, int which) {
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
				
				activityStartTimeCal.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
				activityStartTimeCal.set(Calendar.MINUTE, timePicker.getCurrentMinute());
				buttonActivityStartTime.setText(sdf.format(activityStartTimeCal.getTime()));
				isComplete.add(buttonActivityStartTime);
			}
		}
	}
	
	private class ButtonActivityOverTimeClick implements Button.OnClickListener {

		@Override
		public void onClick(View arg0) {
			TimePicker timePicker = new TimePicker(AddMatchGroupActivity.this);
			
			timePicker.setIs24HourView(true);
			timePicker.setCurrentHour(activityOverTimeCal.get(Calendar.HOUR_OF_DAY));
			timePicker.setCurrentMinute(activityOverTimeCal.get(Calendar.MINUTE));
			timePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
			new AlertDialog.Builder(AddMatchGroupActivity.this)
			.setTitle("選擇活動結束時間")
			.setView(timePicker)
			.setNegativeButton("取消", null)
			.setPositiveButton("確定", new OverTimePickerDialogPositiveClick(timePicker))
			.show();
		}
		
		private class OverTimePickerDialogPositiveClick implements DialogInterface.OnClickListener {
			private TimePicker timePicker;

			public OverTimePickerDialogPositiveClick(TimePicker timePicker) {
				this.timePicker = timePicker;
			}

			@Override
			public void onClick(DialogInterface dialog, int which) {
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
				
				activityOverTimeCal.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
				activityOverTimeCal.set(Calendar.MINUTE, timePicker.getCurrentMinute());
				buttonActivityOverTime.setText(sdf.format(activityOverTimeCal.getTime()));
				isComplete.add(buttonActivityOverTime);
			}
		}
	}
	
	private class EditTextInvitePeopleFocusTouchListener implements EditText.OnTouchListener {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN)
				new InvitePeopleFBHelper().ensureSessionOpenAndDoSomething(AddMatchGroupActivity.this);
			return true;
		}
		
		private class InvitePeopleFBHelper extends FBHelper {

			@Override
			protected void doAfterEnsureSessionOpen() {
				Bundle bundle = new Bundle();
				Intent intent = new Intent(AddMatchGroupActivity.this, PickFriendsActivity.class);
				ArrayList<String> friendIdList = new ArrayList<String>();
				
				for (String id: idFriendMap.keySet())
					friendIdList.add(id);
				bundle.putStringArrayList("friendIdList", friendIdList);
				intent.putExtras(bundle);
		        startActivityForResult(intent, PICK_FRIENDS_ACTIVITY);
			}

			@Override
			protected void doAfterFqlQuery(Response response) {
			}
		}
	}
	
	private class ImageButtonPreviousClickListener implements ImageButton.OnClickListener {

		@Override
		public void onClick(View v) {
			AddMatchGroupActivity.this.finish();
		}
	}
	
	private class ButtonNextClick implements Button.OnClickListener {

		@Override
		public void onClick(View arg0) {
			if (!isComplete.contains(editTextActivityName) ||
					editTextActivityName.getText().toString().equals("")) {
				new AlertDialog.Builder(AddMatchGroupActivity.this)
				.setTitle("尚未填寫活動名稱")
				.setMessage("請填寫活動名稱")
				.setPositiveButton("好", null)
				.show();
			}
			else if (!isComplete.contains(editTextActivityPlace) ||
					editTextActivityPlace.getText().toString().equals("")) {
				new AlertDialog.Builder(AddMatchGroupActivity.this)
				.setTitle("尚未填寫活動地點")
				.setMessage("請填寫活動地點")
				.setPositiveButton("好", null)
				.show();
			}
			else if (!isComplete.contains(buttonStartDate)) {
				new AlertDialog.Builder(AddMatchGroupActivity.this)
				.setTitle("尚未選擇媒合開始日期")
				.setMessage("請選擇媒合開始日期")
				.setPositiveButton("好", null)
				.show();
			}
			else if (!isComplete.contains(buttonOverDate)) {
				new AlertDialog.Builder(AddMatchGroupActivity.this)
				.setTitle("尚未選擇媒合結束日期")
				.setMessage("請選擇媒合結束日期")
				.setPositiveButton("好", null)
				.show();
			}
			else if (CalendarAlgorithm.compareDate(matchStartCal, matchEndCal) == 1) {
				new AlertDialog.Builder(AddMatchGroupActivity.this)
				.setTitle("媒合日期範圍不正確")
				.setMessage("媒合開始日期須小於或等於媒合結束日期")
				.setPositiveButton("好", null)
				.show();
			}
			else if (isComplete.contains(checkBoxAdvanceTimeChoose))
				checkHaveInviteFriendsAndStart();
			else {
				if (!isComplete.contains(buttonActivityStartTime)) {
					new AlertDialog.Builder(AddMatchGroupActivity.this)
					.setTitle("尚未選擇活動開始時間")
					.setMessage("請選擇活動開始時間或使用進階活動時間設定")
					.setPositiveButton("好", null)
					.show();
				}
				else if (!isComplete.contains(buttonActivityOverTime)) {
					new AlertDialog.Builder(AddMatchGroupActivity.this)
					.setTitle("尚未選擇活動結束時間")
					.setMessage("請選擇活動結束時間或使用進階活動時間設定")
					.setPositiveButton("好", null)
					.show();
				}
				else if (CalendarAlgorithm.compareTime(activityStartTimeCal, activityOverTimeCal) >= 0) {
					new AlertDialog.Builder(AddMatchGroupActivity.this)
					.setTitle("活動時間範圍不正確")
					.setMessage("活動開始時間須小於活動結束時間")
					.setPositiveButton("好", null)
					.show();
				}
				else
					checkHaveInviteFriendsAndStart();
			}
		}
		
		private void checkHaveInviteFriendsAndStart() {
			if (idFriendMap.isEmpty()) {
				new AlertDialog.Builder(AddMatchGroupActivity.this)
				.setTitle("尚未選擇邀請對象")
				.setMessage("請選擇邀請對象")
				.setPositiveButton("好", null)
				.show();
			}
			else
				new PostCheckMySchedule().execute();
		}
	}
	
	private class CheckBoxAdvanceTimeChooseCheckedChange implements CheckBox.OnCheckedChangeListener {

		@Override
		public void onCheckedChanged(CompoundButton view, boolean isChecked) {
			if (isChecked) {
				buttonActivityStartTime.setEnabled(false);
				buttonActivityOverTime.setEnabled(false);
				isComplete.add(view);
			}
			else {
				buttonActivityStartTime.setEnabled(true);
				buttonActivityOverTime.setEnabled(true);
				isComplete.remove(view);
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case GOOGLEMAP_REQUEST_CODE:
					editTextActivityPlace.setText(data.getExtras().getString("activityAddr"));
					isComplete.add(editTextActivityPlace);
					break;
				case MATCH_REQUEST_CODE:
					setResult(RESULT_OK);
					AddMatchGroupActivity.this.finish();
					break;
				case PICK_FRIENDS_ACTIVITY:
					String resultFriendNames = "";
					List<FBUser> friendList = data.getExtras().getParcelableArrayList("friendList");
					
					idFriendMap.clear();
					if (friendList.isEmpty())
						editTextInvitePeople.setText("邀請對象");
					else {
						for (FBUser friend: friendList) {
							idFriendMap.put(friend.getId(), friend);
							resultFriendNames += friend.getName() + " ";
						}
						editTextInvitePeople.setText(resultFriendNames);
					}
					break;
				case FINISH_SCHEDULE_REQUEST_CODE:
					new PostCheckMySchedule().execute();
					break;
				default:
					Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
			}
		}
	}
	
	private class PostCheckMySchedule extends AsyncTask<Void, Void, String> {
		private ProgressDialog proDialog;
		
		@Override
		protected void onPreExecute() {
			proDialog = ProgressDialog.show(AddMatchGroupActivity.this, "檢查行程表", "正在檢查您的行程表...");
			proDialog.setCancelable(false);
		}

		@Override
		protected String doInBackground(Void... params) {
			String result = null;
			
			try {
				JSONObject jsonObj = new JSONObject();
				HttpResponse resp;
				
				jsonObj.put("id", getIntent().getExtras().getString("myFBID"));
				resp = HttpHelper.executePost("http://iculture.twgg.org/schedule/checkMySchedule.php", jsonObj.toString());
				result = EntityUtils.toString(resp.getEntity());
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return result;
		}
		
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject jsonObj = new JSONObject(result);
				
				if (jsonObj.getBoolean("haveSchedule"))
					new PostCheckFriendSchedule().execute();
				else {
					proDialog.cancel();
					new AlertDialog.Builder(AddMatchGroupActivity.this)
					.setTitle("尚未完成行程表")
					.setMessage("因您尚未完成行程表所以無法進行媒合\n還麻煩請您先設定行程表")
					.setPositiveButton("設定行程表", new FinishScheduleButtonClickListener())
					.setCancelable(false)
					.show();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		private class FinishScheduleButtonClickListener implements DialogInterface.OnClickListener {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(AddMatchGroupActivity.this, FinishScheduleActivity.class);
				Bundle bundle = new Bundle();
				
				bundle.putString("myFBID", getIntent().getExtras().getString("myFBID"));
				intent.putExtras(bundle);
				startActivityForResult(intent, FINISH_SCHEDULE_REQUEST_CODE);
			}
		}
		
		private class PostCheckFriendSchedule extends AsyncTask<Void, Void, Set<String>> {
			
			@Override
			protected void onPreExecute() {
				proDialog.setMessage("正在檢查朋友的行程表...");
			}

			@Override
			protected Set<String> doInBackground(Void... params) {
				Set<String> friendNoScheduleSet = new HashSet<String>();
				
	            try {
	            	JSONArray jsonArr = new JSONArray();
	            	HttpResponse resp;
	            	JSONArray respJsonArr;
	                    
	            	for (String friendId: idFriendMap.keySet()) {
	            		JSONObject jsonObj = new JSONObject();
	            		
	            		jsonObj.put("id", friendId);
                		jsonArr.put(jsonObj);
	            	}
	            	resp = HttpHelper.executePost("http://iculture.twgg.org/schedule/checkFriendSchedule.php", jsonArr.toString());
	            	respJsonArr = new JSONArray(EntityUtils.toString(resp.getEntity()));
	            	for (int i=0; i<respJsonArr.length(); i++)
	            		friendNoScheduleSet.add(respJsonArr.getJSONObject(i).getString("id"));
	            } catch (JSONException e) {
	            	e.printStackTrace();
	            } catch (ParseException e) {
	            	e.printStackTrace();
	            } catch (IOException e) {
	            	e.printStackTrace();
	            }
	            return friendNoScheduleSet;
			}
			
			@Override
			protected void onPostExecute(Set<String> friendNoScheduleSet) {
				proDialog.cancel();
				if (friendNoScheduleSet.size() == 0) {
					Bundle bundle = new Bundle();
					Intent intent;
					ArrayList<FBUser> friendList = new ArrayList<FBUser>();
					
					bundle.putString("myFBID", getIntent().getExtras().getString("myFBID"));
					bundle.putString("activityName", editTextActivityName.getText().toString());
					bundle.putInt("icon", spinnerIcon.getSelectedItemPosition());
					bundle.putString("activityPlace", editTextActivityPlace.getText().toString());
					bundle.putInt("matchStartYear", matchStartCal.get(Calendar.YEAR));
					bundle.putInt("matchStartMonth", matchStartCal.get(Calendar.MONTH));
					bundle.putInt("matchStartDate", matchStartCal.get(Calendar.DATE));
					bundle.putInt("matchOverYear", matchEndCal.get(Calendar.YEAR));
					bundle.putInt("matchOverMonth", matchEndCal.get(Calendar.MONTH));
					bundle.putInt("matchOverDate", matchEndCal.get(Calendar.DATE));
					for (FBUser friend: idFriendMap.values())
						friendList.add(friend);
					bundle.putParcelableArrayList("friendList", friendList);
					if (isComplete.contains(editTextActivityPS))
						bundle.putString("activityPs", editTextActivityPS.getText().toString());
					else
						bundle.putString("activityPs", "");
					if (isComplete.contains(checkBoxAdvanceTimeChoose))
						intent = new Intent(AddMatchGroupActivity.this, SetMatchScheduleActivity.class);
					else {
						ArrayList<CalendarTextData> matchCalDataList = new ArrayList<CalendarTextData>();
						
						for (int i=0; i<=6; i++) {
							int startHour = activityStartTimeCal.get(Calendar.HOUR_OF_DAY);
							int startMinute = activityStartTimeCal.get(Calendar.MINUTE);
							int overHour = activityOverTimeCal.get(Calendar.HOUR_OF_DAY);
							int overMinute = activityOverTimeCal.get(Calendar.MINUTE);
							
							matchCalDataList.add(new CalendarTextData(i, startHour, startMinute,
									overHour, overMinute, -1, null, null));
						}
						bundle.putParcelableArrayList("matchCalDataList", matchCalDataList);
						intent = new Intent(AddMatchGroupActivity.this, MatchResultActivity.class);
					}
					intent.putExtras(bundle);
					startActivityForResult(intent, MATCH_REQUEST_CODE);
				}
				else {
					List<FBUser> displayFriendList = new ArrayList<FBUser>();
					ListView dialogListView = new ListView(AddMatchGroupActivity.this);
					
					for (String friendId: friendNoScheduleSet)
						displayFriendList.add(idFriendMap.get(friendId));
					dialogListView.setAdapter(new FriendWithNoScheduleListViewAdapter(
							AddMatchGroupActivity.this, android.R.layout.simple_list_item_1, displayFriendList));
					new AlertDialog.Builder(AddMatchGroupActivity.this)
					.setTitle("您的以下朋友尚未設定行程表")
					.setView(dialogListView)
					.setNegativeButton("取消媒合", null)
					.setPositiveButton("忽略他們並且繼續媒合", null)
					.show();
				}
			}
			
			private class FriendWithNoScheduleListViewAdapter extends ArrayAdapter<FBUser> {
				private SparseArray<View> findRow = new SparseArray<View>();
				
				public FriendWithNoScheduleListViewAdapter(
						Context context, int textViewResourceId, List<FBUser> objects) {
					super(context, textViewResourceId, objects);
				}

				@Override
				public View getView(int position, View convertView, ViewGroup parent) {
					if (findRow.get(position) == null) {
						TextView textViewName = new TextView(AddMatchGroupActivity.this);
						Drawable defaultIcon = getResources().getDrawable(R.drawable.com_facebook_profile_default_icon);
						
						textViewName.setCompoundDrawablesWithIntrinsicBounds(defaultIcon, null, null, null);
						textViewName.setGravity(Gravity.CENTER_VERTICAL);
						textViewName.setText(getItem(position).getName());
						findRow.put(position, textViewName);
						new GetFriendPhotos().execute(getItem(position));
						return textViewName;
					}
					else if (getItem(position).getPhoto() == null)
						return findRow.get(position);
					else {
						Drawable defaultIcon = getResources().getDrawable(R.drawable.com_facebook_profile_default_icon);
						Drawable drawableBitmap = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(
								getItem(position).getPhoto(), defaultIcon.getIntrinsicWidth(), defaultIcon.getIntrinsicHeight(), true));
						TextView textViewName = (TextView) findRow.get(position);
						
						textViewName.setCompoundDrawablesWithIntrinsicBounds(drawableBitmap, null, null, null);
						return findRow.get(position);
					}
				}
				
				private class GetFriendPhotos extends GetFBUserPhotoHelper {

					@Override
					protected void onPostExecute(FBUser fbUser) {
						FriendWithNoScheduleListViewAdapter.this.notifyDataSetChanged();
					}
				}
			}
		}
	}
	
	private void setBundleDataFromActivity(Bundle bundle) {
		String[] activityTimeArr, activityStartDateArr;
		int year, month, date;
		
		editTextActivityName.setText(bundle.getString("ACT_NAME"));
		isComplete.add(editTextActivityName);
		editTextActivityPlace.setText(bundle.getString("ACT_LOCATION"));
		isComplete.add(editTextActivityPlace);
		activityTimeArr = bundle.getString("ACT_TIME").split(" ");
		activityStartDateArr = activityTimeArr[0].split("/");
		year = Integer.parseInt(activityStartDateArr[0]);
		month = Integer.parseInt(activityStartDateArr[1]) - 1;
		date = Integer.parseInt(activityStartDateArr[2]);
		matchStartCal.set(year, month, date);
		buttonStartDate.setText(activityTimeArr[0]);
		isComplete.add(buttonStartDate);
		matchEndCal.set(year, month, date);
		buttonOverDate.setText(activityTimeArr[0]);
		isComplete.add(buttonOverDate);
	}
	
	private void setBundleDataFromShake(Bundle bundle) {
		if (bundle.getString("title") != null) {
			editTextActivityName.setText(bundle.getString("title"));
			isComplete.add(editTextActivityName);
		}
		if (bundle.getString("location") != null) {
			editTextActivityPlace.setText(bundle.getString("location"));
			isComplete.add(editTextActivityPlace);
		}
		if (bundle.getString("matchStartDate") != null) {
			String[] matchStartDate = bundle.getString("matchStartDate").split("/");
			int year = Integer.parseInt(matchStartDate[0]);
			int month = Integer.parseInt(matchStartDate[1]) - 1;
			int date = Integer.parseInt(matchStartDate[2]);
			
			matchStartCal.set(year, month, date);
			buttonStartDate.setText(bundle.getString("matchStartDate"));
			isComplete.add(buttonStartDate);
		}
		if (bundle.getString("matchOverDate") != null) {
			String[] matchOverDate = bundle.getString("matchOverDate").split("/");
			int year = Integer.parseInt(matchOverDate[0]);
			int month = Integer.parseInt(matchOverDate[1]) - 1;
			int date = Integer.parseInt(matchOverDate[2]);
			
			matchEndCal.set(year, month, date);
			buttonOverDate.setText(bundle.getString("matchOverDate"));
			isComplete.add(buttonOverDate);
		}
		if (bundle.getString("acStartTime") != null) {
			String[] acStartTime = bundle.getString("acStartTime").split(":");
			
			activityStartTimeCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(acStartTime[0]));
			activityStartTimeCal.set(Calendar.MINUTE, Integer.parseInt(acStartTime[1]));
			buttonActivityStartTime.setText(bundle.getString("acStartTime"));
			isComplete.add(buttonActivityStartTime);
		}
		if (bundle.getString("acOverTime") != null) {
			String[] acOverTime = bundle.getString("acOverTime").split(":");
			
			activityOverTimeCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(acOverTime[0]));
			activityOverTimeCal.set(Calendar.MINUTE, Integer.parseInt(acOverTime[1]));
			buttonActivityOverTime.setText(bundle.getString("acOverTime"));
			isComplete.add(buttonActivityOverTime);
		}
		if (bundle.getParcelable("friend") != null) {
			FBUser friend = bundle.getParcelable("friend");
			
			editTextInvitePeople.setText(friend.getName());
			idFriendMap.put(friend.getId(), friend);
		}
	}
}